#include "fileHandling.h"
#include "../spanishFreq.h"

/*char *
fileToOpen(FILE * fd)
{
   unsigned char * text = NULL;
   int counter = 0;
   unsigned char * aux = text;
      
   if( (text = calloc(sizeof(unsigned char),ITEMS)) == NULL )
	   return NULL;
   
   while( fread(&(text[ITEMS*counter]),sizeof(unsigned char),ITEMS,fd) != 0  ){
      counter++;
	 
	 aux = text;
	 if( (text = realloc(text,(counter+1)*ITEMS)) == NULL ){
	 	free(aux);
	 	return NULL;
	 }
	 	
   }

   text = trim(text);
   aux = text;
   if( (text = realloc(text, strlen(text))) == NULL ){
	 	free(aux);
	 	return NULL;
	 }

   tolowerStr(text);
   
	return text;
   
}*/

unsigned char *
fileToOpen(char* name, long* size)
{
   unsigned char * text = NULL;
   FILE *fd;
    
   fd = fopen("test.txt","rb");

   
   fseek(fd, 0, SEEK_END);
   *size = ftell(fd);
   fseek(fd, 0, SEEK_SET);
   
   if( (text = calloc(*size + 1, sizeof(unsigned char))) == NULL )
      return NULL;

   if( fread(text, sizeof(unsigned char), *size, fd) == 0 )
      return NULL;
   
   text[*size] = 0;
   
   fclose(fd);
   
   //tolowerStr(text);
   
	return text;
   
}

int *
readFile(char* name, long* size)
{
   unsigned char c;
   int * resul, i;
   FILE *fd;
    
   if ( (fd = fopen(name,"rb")) == NULL)
	   return NULL;

   fseek(fd, 0, SEEK_END);
   *size = ftell(fd);
   fseek(fd, 0, SEEK_SET);
   
   if ((resul = calloc(*size, sizeof(int))) == NULL)
      return NULL;

   for (i = 0; i < *size; i++)
   {
      if (fread(&c, sizeof(unsigned char), 1, fd) == 0)
      {
         free(resul);
         return NULL;
      }
      if (c <= 'N')
         resul[i] = c - 'A';
      else if (c == 209)//241
         resul[i] = LETRA_ENIE;
      else
         resul[i] = c - 'A' + 1;
   }
   
   fclose(fd);
   
	return resul;
   
}
